package com.socket.demo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * <h3>Description</h3>
 * TODO
 * <h3>Author</h3> luzhenbang
 * <h3>Date</h3> 2018/4/13 13:57
 * <h3>Copyright</h3> Copyright (c)2018 Shenzhen TL  Co., Ltd. Inc. All rights reserved.
 */
public class ServerSocketTest {
    private static BufferedReader br=null;
    private static PrintWriter pw=null;
    private static int count = 0;
    private static InputStream is;

    public static void main(String[] args) {
        System.out.print("开启服务!");
        Socket socket = null;
        try {
            //创建ServerSocket 绑定端口 要确定端口没有被占用
            ServerSocket ss = new ServerSocket(8080,50);
            //阻塞方法 等待接受客户端
            socket = ss.accept();
            is = socket.getInputStream();
            br=new BufferedReader(new InputStreamReader(is));
            pw=new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));

            System.out.println("连接成功"+ socket.getRemoteSocketAddress());
            while(true){
//                OutputStream os = socket.getOutputStream();
//                os.write("您好，恭喜您中奖了！".getBytes("utf-8"));
//                os.close();
                pw.println("传递数据: " + count);
                pw.flush();
                if (is.available() != 0){
                    //接受客户端的数据
                    String  dataFromClient = br.readLine();
                    //接受到关闭信号进行关闭
                    if (dataFromClient != null && !dataFromClient.isEmpty() && dataFromClient.equals("exit")){
                        socket.close();
                    }
                    System.out.println(dataFromClient);
                }

            }

        } catch (IOException e) {
            if (null != socket){
                try {
                    socket.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (pw != null){
                pw.close();
            }
            if (br != null){
                try {
                    br.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            e.printStackTrace();
        }

    }
}
